package com.woniu.atms.controller.aft;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.woniu.atms.entity.G5Manger;
import com.woniu.atms.entity.G5User;
import com.woniu.atms.service.G5MangerService;
import com.woniu.atms.util.Audience;
import com.woniu.atms.util.Code;
import com.woniu.atms.util.JwtUtil;
import com.woniu.atms.util.ResponseResult;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author 李涵
 * @title: AftMangerController 超级管理员 后台管理员管理
 * @projectName g5_atms
 * @description: TODO
 * @date 2022/1/17 15:25
 */
@RestController
@RequestMapping("/api/aft/v1/manger")
public class AftMangerController {
    @Resource
    private G5MangerService g5MangerService;
    @Resource
    private Audience audience;

    /**
     * 后台管理员列表
     * @param
     * @return ResponseResult<List<G5Manger>>
     */
//    @GetMapping("/list")
//    public ResponseResult<PageInfo<G5Manger>> mangerList(@RequestParam(required = false,defaultValue = "1")Integer pageNum){
//        //TODO
//        PageHelper.startPage(pageNum,1);
//        List<G5Manger> g5Mangers=g5MangerService.list();
//        PageInfo<G5Manger> pageInfo=new PageInfo<>(g5Mangers);
//        return new ResponseResult<>(pageInfo);
//    }

    /**
     * 根据id查询后台管理员
     * @param g5Manger
     * @return ResponseResult<G5Manger>
     */
//    @GetMapping("/info_id")
//    public ResponseResult<G5Manger> findMangerById(@RequestBody G5Manger g5Manger){
//
//        return new ResponseResult<>(g5MangerService.getById(g5Manger.getId()));
//    }
    /**
     * 根据账号查询后台管理员
     * @param g5Manger
     * @return ResponseResult<G5Manger>
     */
//    @GetMapping("/info_account")
//    public ResponseResult<G5Manger> findMangerByAccount(@RequestBody G5Manger g5Manger){
//        QueryWrapper queryWrapper=new QueryWrapper();
//        queryWrapper.eq("account",g5Manger.getAccount());
//        return new ResponseResult<>(g5MangerService.getOne(queryWrapper));
//    }

    /**
     * 管理员登陆
     * @param g5Manger
     * @return
     */
    @RequestMapping("/login")
    public ResponseResult login(@RequestBody G5Manger g5Manger, HttpServletRequest request){
        //获取ip

       String ip=request.getRemoteAddr();



        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("account",g5Manger.getAccount());
        G5Manger manger=g5MangerService.getOne(queryWrapper);
        if(manger!=null){
            if("y".equals(manger.getIsExit())){
                if(manger.getErrorNum()==3&&!manger.getAccount().equals("admin")){
                    return new ResponseResult(Code.FAIL,"密码已经错误三次,联系超级管理员解封");
                }
                queryWrapper.eq("password",g5Manger.getPassword());
                if(g5MangerService.getOne(queryWrapper)!=null){
                    //获取登陆时间
                    manger.setLastLoginTime(new Date());
                    //获取登录ip（前端传入）
                    manger.setLastLoginIp(ip);
                    g5MangerService.updateById(manger);
                    return new ResponseResult(JwtUtil.createJwt(manger.getId(),manger.getAccount(),audience));
                }else {
                    //密码错误，错误次数加1
                    if(manger.getErrorNum()==2&&!manger.getAccount().equals("admin")){
                        manger.setLockTime(new Date());
                    }
                    manger.setErrorNum(manger.getErrorNum()+1);
                    g5MangerService.updateById(manger);
                    return new ResponseResult(Code.FAIL,"密码错误",null);
                }
            }else {
                return new ResponseResult(Code.FAIL,"账号不存在");
            }
            //密码错误3次，不能登录，联系超级管理员
        }
        return new ResponseResult(Code.FAIL,"账号不存在");
    }

    /**
     * 添加管理员
     * @param g5Manger
     * @return
     */
    @RequestMapping("/addManger")
    public  ResponseResult addManger(@RequestBody G5Manger g5Manger){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("account",g5Manger.getAccount());
        G5Manger manger=g5MangerService.getOne(queryWrapper);

        //被删除的
        if(manger!=null){
             if(manger.getIsExit().equals("n")){
                g5Manger.setId(manger.getId());
                g5Manger.setCreateTime(new Date());
                g5Manger.setErrorNum(0);
                g5Manger.setIsExit("y");
                g5MangerService.updateById(g5Manger);
                return new ResponseResult(Code.SUCCESS,"添加成功");
            }else {
                 return new ResponseResult(Code.FAIL,"管理员已存在");
             }
        }
           //未添加的
        else {
            g5Manger.setCreateTime(new Date());
            g5Manger.setErrorNum(0);
            g5Manger.setIsExit("y");
            g5MangerService.save(g5Manger);
            return new ResponseResult(Code.SUCCESS,"添加成功");
        }

    }


    /**
     * 根据id删除后台管理员(逻辑删除)
     * @param g5Manger
     * @return ResponseResult<Boolean>
     */

    @RequestMapping ("/delete")
    public ResponseResult deleteManger(@RequestBody G5Manger g5Manger){
        g5Manger.setIsExit("n");
        return new ResponseResult<>(g5MangerService.updateById(g5Manger));
    }

    @RequestMapping("updatePassword")
    public ResponseResult updatePassword(@RequestBody G5Manger g5Manger,@RequestHeader String aft_token){

        g5MangerService.updateById(g5Manger);
        return new ResponseResult("修改成功");
    }

    @RequestMapping ("/update")
    public ResponseResult updateManger(@RequestBody G5Manger g5Manger){
        g5Manger.setErrorNum(0);
        return new ResponseResult<>(g5MangerService.updateById(g5Manger));
    }

    @RequestMapping ("/mangerInfo")
    public ResponseResult findManger(@RequestBody(required = false) G5Manger g5Manger, @RequestParam(required = false,defaultValue = "1")Integer pageNum,@RequestHeader String aft_token){
        String account=JwtUtil.parseJwtForAccount(aft_token,audience);
        if(!"admin".equals(account)){
            return new ResponseResult(Code.FAIL,"无权访问");
        }

        QueryWrapper queryWrapper=new QueryWrapper();
        if(g5Manger!=null){
            if(g5Manger.getId()!=null){
                queryWrapper.eq("id",g5Manger.getId());
            }
            if(StringUtil.isNotEmpty(g5Manger.getAccount())){
                queryWrapper.like("account",g5Manger.getAccount());
            }
        }
        PageHelper.startPage(pageNum,1);
        List<G5Manger> g5Mangers=g5MangerService.list(queryWrapper);
        PageInfo<G5Manger> pageInfo=new PageInfo<>(g5Mangers);
        return new ResponseResult(pageInfo);
    }
    @RequestMapping("/loginInfo")
    public ResponseResult loginInfo(@RequestHeader String aft_token){
        G5Manger g5Manger=new G5Manger();
        try {
            g5Manger.setId(JwtUtil.parseJwtForId(aft_token,audience));
            g5Manger.setAccount(JwtUtil.parseJwtForAccount(aft_token,audience));
            return new ResponseResult(g5Manger);
        }catch (Exception e){
            return new ResponseResult(Code.FAIL,"登录信息失效，请重新登录");
        }
    }
}
